////////////////////////////////////////////////////////////////////////////////////////
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING THIS SOFTWARE
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install, copy or use the software.
//
// Copyright (C) 2013, AerVision Technologies Pty Ltd, all rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of AerVision Technologies, may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors to demonstrate 
// www.AerCloud.net Framework as a Service API (FaaS), "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the copyright holder or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
////////////////////////////////////////////////////////////////////////////////////////

package com.aercloud.client.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

public class ImageCache {
    
    private static Logger log = Logger.getLogger(ImageCache.class);
    
    private static File getDir(String accessKeyHash) {
        File dir = new File(new File(".", accessKeyHash), "ImageCache");
        dir.mkdirs();
        return dir;
    }
    
    private static File getFile(String accessKeyHash, String personName, String imageName) {
        return new File(getDir(accessKeyHash), new StringBuffer(personName).append(".").append(imageName).append(".png").toString());
    }

    public static BufferedImage getImage(String accessKeyHash, String personName, String imageName) {
        try {
           return ImageIO.read(getFile(accessKeyHash, personName, imageName));
        } catch (IOException e) {
           return null;
        }
    }

    public static void putImage(String accessKeyHash, String personName, String imageName, BufferedImage image) {
        if(image != null) try {
            ImageIO.write(image, "png", getFile(accessKeyHash, personName, imageName));
        } catch (IOException e) {
            log.error("Error caching image: " + imageName, e);
        }
    }

    public static void deleteImage(String accessKeyHash, String personName, String imageName) {
        try {
            if(!getFile(accessKeyHash, personName, imageName).delete()) {
                log.error("Failed to delete image from cache: " + imageName);
            }
        } catch(Exception e) {
            log.error("Error deleting image from cache: " + imageName, e);
        }
    }
    
    public static void deleteAllImages(String accessKeyHash, String personName) {
        final String filenamePrefix = new StringBuffer(personName).append(".").toString();
        getDir(accessKeyHash).listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if(pathname.getName().startsWith(filenamePrefix)) try {
                    if(!pathname.delete()) {
                        log.error("Failed to delete image from cache: " + pathname.getName());
                    }
                } catch(Exception e) {
                    log.error("Error deleting image from cache: " + pathname.getName(), e);
                }
                return false;
            }
        });
    }

    public static boolean imageExists(String accessKeyHash, String personName, String imageName) {
        return getFile(accessKeyHash, personName, imageName).exists();
    }

    public static void clearCache(String accessKeyHash) {
        for(File f : getDir(accessKeyHash).listFiles()) {
            try {
                if(!f.delete()) {
                    log.error("Failed to delete a file from cache: " + f.getName());
                }
            } catch(Exception e) {
                log.error("Error deleting a file from cache: " + f.getName(), e);
            }
        }
    }

}
